import { ipcRenderer, contextBridge } from 'electron'

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('ipcRenderer', {
  on(...args: Parameters<typeof ipcRenderer.on>) {
    const [channel, listener] = args
    return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
  },
  off(...args: Parameters<typeof ipcRenderer.off>) {
    const [channel, ...omit] = args
    return ipcRenderer.off(channel, ...omit)
  },
  send(...args: Parameters<typeof ipcRenderer.send>) {
    const [channel, ...omit] = args
    return ipcRenderer.send(channel, ...omit)
  },
  invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
    const [channel, ...omit] = args
    return ipcRenderer.invoke(channel, ...omit)
  },

})

// --------- Preload scripts loading ---------
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {
  return new Promise((resolve) => {
    if (condition.includes(document.readyState)) {
      resolve(true)
    } else {
      document.addEventListener('readystatechange', () => {
        if (condition.includes(document.readyState)) {
          resolve(true)
        }
      })
    }
  })
}

const safeDOM = {
  append(parent: HTMLElement, child: HTMLElement) {
    if (!Array.from(parent.children).find(e => e === child)) {
      return parent.appendChild(child)
    }
  },
  remove(parent: HTMLElement, child: HTMLElement) {
    if (Array.from(parent.children).find(e => e === child)) {
      return parent.removeChild(child)
    }
  },
}

/**
 * https://tobiasahlin.com/spinkit
 * https://connoratherton.com/loaders
 * https://projects.lukehaas.me/css-loaders
 * https://matejkustec.github.io/SpinThatShit
 */
function useLoading() {
  const className = `loaders-css__square-spin`
  const styleContent = `
@keyframes square-spin {
  25% { transform: perspective(100px) rotateX(180deg) rotateY(0); }
  50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); }
  75% { transform: perspective(100px) rotateX(0) rotateY(180deg); }
  100% { transform: perspective(100px) rotateX(0) rotateY(0); }
}
.${className} > div {
  animation-fill-mode: both;
  width: 50px;
  height: 50px;
  background: #fff;
  animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite;
}
.app-loading-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #282c34;
  z-index: 9;
}
    `
  const oStyle = document.createElement('style')
  const oDiv = document.createElement('div')

  oStyle.id = 'app-loading-style'
  oStyle.innerHTML = styleContent
  oDiv.className = 'app-loading-wrap'
  oDiv.innerHTML = `<div class="${className}"><div></div></div>`

  return {
    appendLoading() {
      safeDOM.append(document.head, oStyle)
      safeDOM.append(document.body, oDiv)
    },
    removeLoading() {
      safeDOM.remove(document.head, oStyle)
      safeDOM.remove(document.body, oDiv)
    },
  }
}

// ----------------------------------------------------------------------

const { appendLoading, removeLoading } = useLoading()
domReady().then(appendLoading)

window.onmessage = (ev) => {
  ev.data.payload === 'removeLoading' && removeLoading()
}

setTimeout(removeLoading, 4999)


//BOSS直聘自动化方法注册
contextBridge.exposeInMainWorld('bossHandleApi', {
  // 注册获取cookie的方法
  getCookies: () => ipcRenderer.invoke('get-cookies'),
  testCommit: ()=>ipcRenderer.invoke('test-commit'),
//   SQL数据处理
  dbSelect: (data)=>ipcRenderer.invoke('db-select',data),
//   SQL数据插入
  dbInsert: (data)=>ipcRenderer.invoke('db-insert',data),
//   用户提交表单的插入
  dbJobFormInsert: (data) => ipcRenderer.invoke('db-job-form-insert',data),
//   用户提交信息查询
  dbJobFormSelect: (data) => ipcRenderer.invoke('db-job-form-select',data),
//  批量删除操作
  dbDelete:(data)=>ipcRenderer.invoke('db-delete',data),
  //db-delete-all 一键清除
  dbDeleteAll:()=>ipcRenderer.invoke('db-delete-all'),
//   db-total
  dbTotal: (data)=>ipcRenderer.invoke('db-total',data),
//   设置全部的值为已失效
  allDataInvalid:(data)=>ipcRenderer.invoke('all-data-invalid',data),
//   不同窗口下的参数信息
  pauseScript:(data)=>ipcRenderer.invoke('pause-script',data),
//stopScript
  stopScript:()=>ipcRenderer.invoke('stop-script'),
//   获取投递成状态
  getDeliveryStatus:()=>ipcRenderer.invoke('get-delivery-status'),
  //greetTitle 打招呼
  greetTitle:(data)=>ipcRenderer.invoke('greet-title',data),
  //  user_config设置
  dbUserConfigSelect:(data)=>ipcRenderer.invoke('db-user-config-select',data),
  dbUserConfigDelete:(data)=>ipcRenderer.invoke('db-user-config-delete',data),
  dbUserConfigUpdate:(data)=>ipcRenderer.invoke('db-user-config-update',data),
  dbUserConfigInsert:(data)=>ipcRenderer.invoke('db-user-config-insert',data),
});

// send 和 invoke分开
contextBridge.exposeInMainWorld('bossSendApi',{
  //   ai接口
  aiSimulatedDelivery:(data)=>ipcRenderer.send('ai-simulated-delivery',data),
  //模拟投递操作 -- 用户地区筛选
  simulatedDelivery: (condition) => {
    ipcRenderer.send('simulated-delivery', condition);
  },
  selectCardCondition:(condition)=>{
    ipcRenderer.send('select-card-condition',condition)
  },
})



